// miniprogram/pages/ucenter/apply_invitation/apply_invitation_list.js
const app = getApp()
const request = require('../../../utils/request.js')
const config = require('../../../utils/config.js')

Page({
  data: {
    colorTheme: app.globalData.colorTheme,
    pageNum: 1,
    pageSize: 50,
    tabNav: ['团队申请', '入队申请', '发出邀请', '收到邀请'],
    TabCur: 0,
    userApplyList: [],
    userInvitedList: [],
    teamInviteList: [],
    teamAppliedList: [],
    statusList: [-1, 0, 1], // -1:拒绝 0:处理中 1:同意
    statusIndex: null,
    countList: [199, 10, 20, 0],
    id1: null, // 申请/邀请的id
    animationTime: 0.4,
    query1: "",
    hasResult: true
  },

  /**
   * 获取用户发出的申请列表
   */
  getUserApplyList: function(pageNum, pageSize, status) {
    let that = this;
    let url = config.SERVER_URL + 'teams/listUserApplyMsg?pageNum=' + pageNum + '&pageSize=' + pageSize + '&status=' + status;
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '加载ing...'
    })
    request.requestGetApi(url, token, {}, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        let hasResult = res.data.rows.length >= pageSize;
        this.setData({
          userApplyList: this.data.userApplyList.concat(res.data.rows),
          hasResult
        });
      }
    }).catch((err) => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
  },

  /**
   * 获取收到的入队申请列表
   */
  getTeamAppliedList: function(pageNum, pageSize, status) {
    let that = this;
    let url = config.SERVER_URL + 'teams/listTeamApplyMsg?pageNum=' + pageNum +
      '&pageSize=' + pageSize + '&status=' + status;
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '加载ing',
    });
    request.requestGetApi(url, token, {}, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        let hasResult = res.data.rows.length >= pageSize;
        this.setData({
          teamAppliedList: this.data.teamAppliedList.concat(res.data.rows),
          hasResult
        });
      }
    }).catch((err) => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
  },

  /**
   * 获取团队对用户发出的邀请列表
   */
  getTeamInviteList: function(pageNum, pageSize, status) {
    let that = this;
    let url = config.SERVER_URL + 'teams/listTeamInviteMsg?pageNum=' + pageNum +
      '&pageSize=' + pageSize + '&status=' + status;
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '加载ing',
    });
    request.requestGetApi(url, token, {}, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        let hasResult = res.data.rows.length >= pageSize;
        this.setData({
          teamInviteList: this.data.teamInviteList.concat(res.data.rows),
          hasResult
        })
      }
    }).catch((err) => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
  },

  /**
   * 获取用户收到的入队邀请
   */
  getUserInvitedList(pageNum, pageSize, status) {
    let that = this;
    let url = config.SERVER_URL + 'teams/listUserInviteMsg?pageNum=' + pageNum + '&pageSize=' + pageSize + '&status=' + status;
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '加载ing',
    });
    request.requestGetApi(url, token, {}, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        let hasResult = res.data.rows.length >= pageSize;
        this.setData({
          userInvitedList: this.data.userInvitedList.concat(res.data.rows),
          hasResult
        })
      }
    }).catch((err) => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
  },

  /**
   * 同意or拒绝入队申请（提交表单）
   */
  submitApplyForm(e) {
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'teams/teamDealWithApplication';
    let params = e.detail.value;
    params.ids = [];
    params.ids = params.ids.concat(params.id);
    let index = params.listIndex;
    delete params.id;
    delete params.listIndex;
    request.requestPostApi(url, token, params, "application/json").then(res=>{
      if (res.status === config.STATUS_OK) {
        wx.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 2000
        });
        that.hideModal();
        // 更新本地数据
        let teamAppliedList = that.data.teamAppliedList;
        let countList = that.data.countList;
        countList[that.data.TabCur] = countList[that.data.TabCur] - 1;
        teamAppliedList[index].status = params.status == 1 ? '同意' : '拒绝';
        teamAppliedList[index].message = params.reason;
        that.setData({
          teamAppliedList: teamAppliedList,
          countList: countList
        });
      }
    }).catch((err) => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
  },

  /**
   * 同意or拒绝入队邀请（提交表单）
   */
  submitInviteForm(e) {
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'teams/userDealWithInvitation';
    let params = e.detail.value;
    params.ids = [];
    params.ids = params.ids.concat(params.id);
    let index = params.listIndex;
    delete params.id;
    delete params.listIndex;
    request.requestPostApi(url, token, params, "application/json").then(res=>{
      if (res.status === config.STATUS_OK) {
        wx.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 2000
        });
        that.hideModal();
        // 更新本地数据
        let userInvitedList = that.data.userInvitedList;
        let countList = that.data.countList;
        countList[that.data.TabCur] = countList[that.data.TabCur] - 1;
        userInvitedList[index].status = params.status == 1 ? '同意' : '拒绝';
        userInvitedList[index].message = params.reason;
        that.setData({
          userInvitedList: userInvitedList,
          countList: countList
        })
      }
    }).catch((err) => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
  },

  /**
   * 查看用户展示页
   */
  goUserShowPage: function(e){
    let uid = e.currentTarget.dataset.uid;
    wx.navigateTo({
      url: '/pages/user-show-info/user-show-info?uid=' + uid,
    })
  },

  // 查看团队展示页
  goTeamShowPage: function(e){
    let teamId = e.currentTarget.dataset.teamid;
    wx.navigateTo({
      url: '/pages/team-show-info/team-show-info?teamId=' + teamId,
    })
  },

  /**
   * 模态框
   */
  showModal(e) {
    let id1 = e.currentTarget.dataset.id1;
    let status1 = e.currentTarget.dataset.status1;
    let listIndex = e.currentTarget.dataset.index;
    if (id1 || status1 || listIndex) {
      this.setData({
        id1: id1,
        status1: status1,
        listIndex: listIndex
      })
    }
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null,
      id1: null,
      status1: null,
      listIndex: null,
      query: ""
    })
  },

  /**
   * 切换tab
   */
  tabSelect(e) {
    this.setData({
      pageNum: 1,
      pageSize: 5,
      userApplyList: [],
      userInvitedList: [],
      teamInviteList: [],
      teamAppliedList: [],
      hasResult: true
    })
    let id = e.currentTarget.dataset.id;
    let index = this.data.statusIndex;
    // 不同tap请求不同数据
    if (id == 0) {
      this.getUserApplyList(this.data.pageNum, this.data.pageSize, index ? statusList[index] : '');
    }
    if (id == 1) {
      this.getTeamAppliedList(this.data.pageNum, this.data.pageSize, index ? statusList[index] : '');
    }
    if (id == 2) {
      this.getTeamInviteList(this.data.pageNum, this.data.pageSize, index ? statusList[index] : '');
    }
    if(id == 3){
      this.getUserInvitedList(this.data.pageNum, this.data.pageSize, index ? statusList[index] : '');
    }
    this.setData({
      TabCur: id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      countList: options.countList.split(',')
    });
    // 加载用户发出的申请列表
    let index = this.data.statusIndex;
    this.getUserApplyList(this.data.pageNum, this.data.pageSize, index ? statusList[index] : '');
  },

  /**
   * 拉到底部
   */
  scrolltolower: function() {
    if(!this.data.hasResult){
      return;
    }
    let pageNum = this.data.pageNum + 1;
    let pageSize = this.data.pageSize;
    let status = this.data.statusIndex ? statusList[index] : '';
    if (this.data.TabCur == 0) {
      this.getUserApplyList(pageNum, pageSize, status);
    }
    if (this.data.TabCur == 1) {
      this.getTeamAppliedList(pageNum, pageSize, status);
    }
    if (this.data.TabCur == 2) {
      this.getTeamInviteList(pageNum, pageSize, status);
    }
    if(this.data.TabCur == 3){
      this.getUserInvitedList(pageNum, pageSize, status);
    }
    this.setData({
      pageNum: pageNum
    })
  }
})